import React from 'react';
import { connect } from 'react-redux';
import { getInputChangeAction, getAddItemAction, getDeleteItemAction } from './store/actionCreators';

// 无状态 UI 组件
const TodoList = props => {
	const { inputValue, list, changeInputValue, buttonClick, deleteClick } = props;

	return (
		<div>
			<div>
				<input value={inputValue} onChange={changeInputValue} />
				<button onClick={buttonClick}>submit</button>
			</div>
			<ul>
				{list.map((item, index) => {
					return (
						<li
							key={index}
							onClick={() => {
								deleteClick(index);
							}}
						>
							{item}
						</li>
					);
				})}
			</ul>
		</div>
	);
};

// 把 state 挂载到 props
const mapStateToProps = state => {
	return {
		inputValue: state.inputValue,
		list: state.list
	};
};

// 把 store.dispatch 方法挂载到 props
const mapDispathToProps = dispatch => {
	return {
		changeInputValue(e) {
			const action = getInputChangeAction(e.target.value);
			dispatch(action);
		},
		buttonClick() {
			const action = getAddItemAction();
			dispatch(action);
		},
		deleteClick(index) {
			const action = getDeleteItemAction(index);
			dispatch(action);
		}
	};
};

export default connect(
	mapStateToProps,
	mapDispathToProps
)(TodoList);
